import { Component } from "react";
import Router from "next/router";
import { connect } from "react-redux";
import { Row, Col, Button, Dropdown, Form, Menu, Icon, Collapse, Input, List, Avatar, Modal } from "antd";
import {
  getAllArticles,
  createNewArticle,
  getAllCollects,
  createNewCollect,
  getArticleById,
  updateArticle
} from "../../redux/actions";
import uuid from "react-uuid";

const { Panel } = Collapse;

@connect(
  ({ article, articles, collects }) => {
    return { article, articles, collects };
  },
  { createNewCollect, getAllArticles, getAllCollects, getArticleById, createNewArticle, updateArticle }
)
class MDEditor extends Component {
  constructor(props) {
    super(props);
    this.state = {
      activeKey: [],
      visible: false,
      modelTitle: "",
      newName: ""
    };

    this.smde = null;

    this.getNameChange = e => {
      this.setState({
        newName: e.target.value
      });
    };

    this.pickUpCollapse = () => {
      this.setState({ activeKey: [] });
    };

    this.collapseChange = key => {
      this.setState({ activeKey: key });
    };

    this.setMarkdownValue = value => {
      this.smde.codemirror.setValue(value);
    };

    this.selectArticle = async item => {
      const article = await this.props.getArticleById({ id: item.WriteID });
      if (article) {
        this.setMarkdownValue(article.markdown);
      }
    };
  }

  async componentDidMount() {
    await this.renderSimpleMarkdown();
    await this.props.getAllCollects();
    const articles = await this.props.getAllArticles();
    const article = await this.props.getArticleById({ id: articles[0].WriteID });
    this.setMarkdownValue(article.markdown);
  }

  async renderSimpleMarkdown() {
    const SimpleMDE = await import("simplemde");
    const marked = await import("marked");
    const hljs = await import("highlight.js");
    const _this = this;

    document
      .getElementById("markdownEditor")
      .parentNode // 获取编辑器container
      .addEventListener("click", e => e.stopPropagation());

    this.smde = new SimpleMDE.default({
      element: document.getElementById("markdownEditor").childElementCount,
      autofocus: true,
      autosave: true,
      initialValue: "",
      indentWithTabs: false,
      placeholder: "## 请输入内容......",
      renderingConfig: {
        singleLineBreaks: false,
        codeSyntaxHighlighting: true
      },
      insertTexts: {
        horizontalRule: ["", "\n\n-----\n\n"],
        image: ["![](http://", ")"],
        link: ["[", "](http://)"],
        table: [
          "",
          "\n\n| Column 1 | Column 2 | Column 3 |\n| -------- | -------- | -------- |\n| Text     | Text      | Text     |\n\n"
        ]
      },
      toolbar: [
        "bold",
        "heading",
        "code",
        "quote",
        "unordered-list",
        "ordered-list",
        "link",
        "image",
        "table",
        "horizontal-rule",
        "preview",
        "side-by-side",
        "fullscreen",
        "guide",
        {
          name: "发布文章",
          action: async function customFunction(editor) {
            const { article } = _this.props;
            _this.props.updateArticle({
              id: article.WriteID,
              markdown: editor.value(),
              html: editor.markdown(editor.value()),
              collectID: 24,
              collectName: "默认文集"
            });
          },
          className: "fa fa-leanpub",
          title: "发布文章"
        }
      ],
      previewRender: function(plainText) {
        return marked.default(plainText, {
          renderer: new marked.default.Renderer(),
          gfm: true,
          pedantic: false,
          sanitize: false,
          tables: true,
          breaks: true,
          smartLists: true,
          smartypants: true,
          highlight: function(code) {
            return hljs.default.highlightAuto(code).value;
          }
        });
      },
      spellChecker: false
    });
  }

  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFields(async (err, values) => {
      if (!err) {
        await this.props.createNewCollect({
          collectName: values.collectName,
          description: "",
          collectTags: ""
        });
      }
    });
  };

  showModal = type => {
    let state = { visible: true };
    if (type === "editArticle") {
      state = { ...state, modelTitle: "修改文章" };
    }
    if (type === "newArticle") {
      state = { ...state, modelTitle: "新建文章" };
    }
    this.setState(state);
  };

  handleOk = e => {
    const { modelTitle, newName } = this.state;
    if (modelTitle === "新建文章") {
      this.props.createNewArticle({
        Title: newName || "",
        collectName: "",
        collectID: 23,
        markdown: "",
        html: ""
      });
    }
  };

  handleCancel = e => {
    this.setState({
      visible: false
    });
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { activeKey, visible, modelTitle } = this.state;
    const { articles, collects, article } = this.props;

    const menu = (
      <Menu>
        <Menu.Item>
          <a target="_blank" rel="noopener noreferrer" href="http://www.alipay.com/">
            修改文集
          </a>
        </Menu.Item>
        <Menu.Divider />
        <Menu.Item>
          <a target="_blank" rel="noopener noreferrer" href="http://www.taobao.com/">
            删除文集
          </a>
        </Menu.Item>
      </Menu>
    );
    const articlemenu = (
      <Menu>
        <Menu.Item>
          <a
            onClick={() => {
              this.showModal("editArticle");
            }}
          >
            修改文章
          </a>
        </Menu.Item>
        <Menu.Divider />
        <Menu.Item>
          <a target="_blank" rel="noopener noreferrer" href="http://www.taobao.com/">
            删除文章
          </a>
        </Menu.Item>
      </Menu>
    );

    return (
      <>
        <Modal
          title={modelTitle}
          visible={visible}
          cancelText="取消"
          okText="提交"
          onOk={this.handleOk}
          onCancel={this.handleCancel}
        >
          <p>
            <span>名称</span>
            <span> : </span>
            <Input style={{ width: "80%" }} placeholder="请输入新名称" onChange={this.getNameChange} />
          </p>
        </Modal>
        <Row className="edit-area" style={{ height: "100%", overflow: "hidden" }}>
          <Col span={4} className="collect-list">
            <div className="back-btn">
              <Button
                type="danger"
                block
                ghost
                onClick={() => {
                  Router.push("/home");
                }}
              >
                回首页
              </Button>
            </div>
            <Collapse
              expandIconPosition="left"
              activeKey={activeKey}
              onChange={this.collapseChange}
              expandIcon={panelProps => <Icon type="plus" />}
            >
              <Panel header="新建文集" key="one">
                <Form onSubmit={this.handleSubmit} className="login-form">
                  <Form.Item>{getFieldDecorator("collectName")(<Input placeholder="请输入文集名称" />)}</Form.Item>{" "}
                  <Button type="primary" htmlType="submit" type="danger" ghost size="small">
                    提交
                  </Button>
                  <Button style={{ marginLeft: "5px" }} type="dashed" ghost size="small" onClick={this.pickUpCollapse}>
                    取消
                  </Button>
                </Form>
              </Panel>
            </Collapse>
            <Menu onClick={this.handleClick} mode="inline">
              {collects &&
                collects.map(item => {
                  return (
                    <Menu.Item key={uuid()}>
                      <Dropdown overlay={menu} placement="bottomRight" trigger={["click", "contextMenu"]}>
                        <Icon type="setting" />
                      </Dropdown>
                      {item.collectName}
                    </Menu.Item>
                  );
                })}
            </Menu>
          </Col>
          <Col span={5} className="article-list">
            {articles ? (
              <List
                size="large"
                header={
                  <div
                    style={{ cursor: "pointer" }}
                    onClick={() => {
                      this.showModal("newArticle");
                    }}
                  >
                    <Icon type="plus-circle" theme="filled" style={{ marginRight: "8px" }} />
                    新建文章
                  </div>
                }
                footer={
                  <div
                    style={{ cursor: "pointer" }}
                    onClick={() => {
                      this.showModal("newArticle");
                    }}
                  >
                    <Icon type="plus-circle" theme="filled" style={{ marginRight: "8px" }} />
                    在下方新建文章
                  </div>
                }
                dataSource={articles || []}
                renderItem={item => (
                  <List.Item
                    onClick={() => this.selectArticle(item)}
                    style={article && article.WriteID === item.WriteID ? { backgroundColor: "#e6e6e6" } : {}}
                  >
                    <List.Item.Meta
                      avatar={
                        <Avatar src="" />
                      }
                      title={item.Title || ""}
                    />
                    <div>
                      <Dropdown overlay={articlemenu} placement="bottomCenter" trigger={["click", "contextMenu"]}>
                        <Icon type="setting" />
                      </Dropdown>
                    </div>
                  </List.Item>
                )}
              />
            ) : null}
          </Col>
          <Col span={15} className="markdown-area">
            <div id="editorContaienr" className="markdown-body">
              <textarea id="markdownEditor"></textarea>
            </div>
          </Col>
        </Row>
      </>
    );
  }
}

const WrapperMDEditor = Form.create({ name: "normal_login" })(MDEditor);
export default WrapperMDEditor;
